﻿using HomagChina.Basic.CCT.Db.CCT_Db;
using System.IO.Ports;
using System.Linq;
using Untilly;

namespace Proxy
{
    public class ManualScanner
    {
        private InsertInfoHandle Handle_Insert;
        private SearchInfoHandle Handle_Search;

        public ManualScanner(string comName, int baud)
        {
            Handle_Insert = new InsertInfoHandle();
            Handle_Search = new SearchInfoHandle();
            InitSerialPort(comName, baud);
        }

        public void InitSerialPort(string comName, int baud)
        {
            var ManualScanner = SerialPortsHelper.OpenClosePort(comName, baud);
            ManualScanner.DataReceived += ManualScanner_DataReceived;
        }

        private void ManualScanner_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            SerialPort _SerialPort = (SerialPort)sender;

            int _bytesToRead = _SerialPort.BytesToRead;
            byte[] recvData = new byte[_bytesToRead];

            _SerialPort.Read(recvData, 0, recvData.Length);

            string Reference = System.Text.UTF8Encoding.UTF8.GetString(recvData).Replace('\r', ' ').Trim();

            if (string.IsNullOrWhiteSpace(Reference))
            {
                return;
            }
            T_BoardInfo t_BoardInfo = Handle_Search.GetPartInfoByReference(Reference);

            if (t_BoardInfo == null)
            {
                HomagGroup.Base.UI.Windows.MessageBox.Show("该板件数据不存在");
                return;
            }

            T_TransOnlineRecords t_TransOnlineRecords = new T_TransOnlineRecords();

            //查看当前线上所有的板件
            var OnlineInfo = Handle_Search.GetTransOnLineInfo();
            if (OnlineInfo != null)
            {
                //查看230机器内当前是否有板
                if (OnlineInfo.Where(s => s.RouteId == 3
                && (s.Location == "111" || s.Location == "20" || s.Location == "10")).Count() == 0)
                {
                    //230空闲，给板
                    t_TransOnlineRecords.RouteId = 3;
                }
                else
                {
                    //去330任意通道
                    t_TransOnlineRecords.RouteId = 1;// 2
                }
            }
            else
            {
                //第一张板子
                t_TransOnlineRecords.RouteId = 1;
            }

            t_TransOnlineRecords.Reference = t_BoardInfo.Reference;

            var InfeedInfo = Handle_Search.GetTransOnLineInfoByLocation();

            if (!InfeedInfo.Reference.Equals(Reference))
            {
                //将Reference存入数据库
                Handle_Insert.InsertOnlinePart(t_TransOnlineRecords);
            }
        }
    }
}